package com.lgd.factoryattendance.Activity;

import static com.lgd.factoryattendance.R.color.royalblue;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.AssemblyManagement;
import com.lgd.factoryattendance.Bean.CustomElectricReportBean;
import com.lgd.factoryattendance.Bean.ElectricSpinnerBean;
import com.lgd.factoryattendance.Bean.ElectricalAssembly;
import com.lgd.factoryattendance.Bean.FactoryAbnormalIssues;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    TextView EmployeeName_TV, group2_TV, cardNumber2_TV, startTime_TV,
            endTime_TV,actualTime_TV,deviceInfo_TV,clockType_TV,tv_timeDeductTips,
            tv_RemainingTime,tv_otherTime;
    Button infoSubmit_BT,electricSubmit_BT;
    TextView showMore_TV;  // 查看更多
    ImageView showMore_IV;
    private boolean isExpanded = false;     // text 折叠文本状态
//    private List<String> assemblynameList = new ArrayList<>();   // 部装列表
//    private ArrayList<ElectricSpinnerBean> spinnerBeanArrayList = null;// 电气列表
    TextView projectName_TV,aCode_TV,serialNumber_TV;
//    Spinner assemblyName_SP ,electric_SP;
    ArrayAdapter<String> assemblyName_adapter;
    String endTime_str = "";  // 结束时间
    String actualTime_str;  // 实际刷卡工时
    Long workhourid;        // 工单 id
    EditText completionProgress_ET, et_suggest;
    ImageView iv_back, iv_refresh;
    RadioGroup exceedTime_RG;
    RadioButton exceedTimeNo_RB;
    Long project_l;  // 项目id
//    时间选择
    LinearLayout downTime_layout ,selectionTime_layout,afterWorkTime_layout,
                    layout_other,layout_close;
    TextView downTime_TV , tv_electric_name ,tv_electric_specification, tv_assembly_name;
    private String time;
    int type = 1; //  1 为正常打卡   2 为异常工单
    Long userid ,deptId , electricAssablyId, projectID;
    String clocktype, electricBCODE;
    int showSpinner = 0;  // 0 为 车间整理   1 为 部装下拉框可见  2 为 电气装配下拉框可见
//    Long electricId;

    Button bt_addSublayout;
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    LinearLayout layout_parent, layout_otherWork,layout_projectName,layout_aCode, layout_electric_name,
            layout_specification, layout_assembly_name, layout_suggestion;
    private ArrayList<CustomElectricReportBean> electricReportBeanArrayList = null;
    String str_otherHours, producedate, androidId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initDate();
    }

    public void init(){
        et_suggest = findViewById(R.id.et_suggest);
        layout_suggestion = findViewById(R.id.layout_suggestion);
        tv_assembly_name = findViewById(R.id.tv_assembly_name);
        layout_assembly_name = findViewById(R.id.layout_assembly_name);
        layout_electric_name = findViewById(R.id.layout_electric_name);
        tv_electric_name = findViewById(R.id.tv_electric_name);
        layout_specification = findViewById(R.id.layout_specification);
        tv_electric_specification = findViewById(R.id.tv_electric_specification);
        androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        layout_close = findViewById(R.id.layout_close);
        layout_close.setOnClickListener(this);
        layout_other = findViewById(R.id.layout_other);
        tv_otherTime = findViewById(R.id.tv_otherTime);
        tv_RemainingTime = findViewById(R.id.tv_RemainingTime);
        tv_timeDeductTips = findViewById(R.id.tv_timeDeductTips);
        layout_aCode = findViewById(R.id.layout_aCode);
        layout_projectName = findViewById(R.id.layout_projectName);
        layout_otherWork = findViewById(R.id.layout_otherWork);
        electricSubmit_BT = findViewById(R.id.electricSubmit_BT);
        electricSubmit_BT.setOnClickListener(this);
        layout_parent = findViewById(R.id.layout_parent);
        bt_addSublayout = findViewById(R.id.bt_addSublayout);
        bt_addSublayout.setOnClickListener(this);
        clockType_TV = findViewById(R.id.clockType_TV);
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        afterWorkTime_layout = findViewById(R.id.afterWorkTime_layout);
        selectionTime_layout = findViewById(R.id.selectionTime_layout);
        downTime_TV = findViewById(R.id.downTime_TV);
        downTime_layout = findViewById(R.id.downTime_layout);
        downTime_layout.setOnClickListener(this);
        exceedTimeNo_RB = findViewById(R.id.exceedTimeNo_RB);
        exceedTime_RG = findViewById(R.id.exceedTime_RG);
        completionProgress_ET = findViewById(R.id.completionProgress_ET);
        completionProgress_ET.addTextChangedListener(inputWatch(completionProgress_ET));  //  限制输入框 范围
        aCode_TV = findViewById(R.id.aCode_TV);
        projectName_TV = findViewById(R.id.projectName_TV);
        EmployeeName_TV = findViewById(R.id.EmployeeName_TV);
        group2_TV = findViewById(R.id.group2_TV);
        cardNumber2_TV = findViewById(R.id.cardNumber2_TV);
        startTime_TV = findViewById(R.id.startTime_TV);
        endTime_TV = findViewById(R.id.endTime_TV);
        actualTime_TV = findViewById(R.id.actualTime_TV);
        infoSubmit_BT = findViewById(R.id.infoSubmit_BT);
        infoSubmit_BT.setOnClickListener(this);

    }
    public void initDate(){
        Intent intent = getIntent();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                workhourid = intent.getLongExtra("workhourid",0);
                System.out.println(workhourid+"----idddd -----");
                if (workhourid == 0){
                    tipsPop();
                    setAlpha(0.2f);
                    tips_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            setAlpha(1.0f);
                        }
                    });
                }else {
                    endTime_str = intent.getStringExtra("endTime");
                    if (TextUtils.isEmpty(endTime_str)){
                        selectionTime_layout.setVisibility(View.VISIBLE);
                        afterWorkTime_layout.setVisibility(View.GONE);
                        type = 2;
                    }else {
                        selectionTime_layout.setVisibility(View.GONE);
                        afterWorkTime_layout.setVisibility(View.VISIBLE);
                        type = 1;
                    }
                    WorkHourStatistics w = new WorkHourStatistics();
                    w.setWorkhourid(workhourid);
                    findWorkHour(w);
                }
            }
        },500);
        exceedTime_RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                String exceedTime_str = radioButton.getText().toString();
                if (exceedTime_str.equals("有其他工作") ){
                    if (actualTime_TV.getText().toString().equals("")){
                        ToastUtils.warnShowLong(getApplicationContext(),"工作时长不为空，请选择时长！！");
                        exceedTimeNo_RB.setChecked(true);
                    }else {
                        otherHoursReportPop();
                        setAlpha(0.35f);
//                          监听弹窗是否 关闭
                        otherReport_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                exceedTimeNo_RB.setChecked(true);
                                setAlpha(1.0f);
                                System.out.println("-----弹窗关闭--------");
                                reStartActivity();
                            }
                        });
                    }
                }
            }
        });
//        ProjectManagement p = new ProjectManagement();
//        findProjectName(p);

        projectType(); // 项目类型

        FactoryAbnormalIssues f = new FactoryAbnormalIssues();
        abnormalCause(f);
    }

//    public void SetAbnormalCause(){
//        FactoryAbnormalIssues f = new FactoryAbnormalIssues();
//        f.setAbnormalType("");
//    }

//    弹窗 遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }
    StringBuilder sb = new StringBuilder();
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.infoSubmit_BT:
                String completionProgress_str = completionProgress_ET.getText().toString();
                if (completionProgress_str.length() != 0){
                    if (actualTime_TV.getText().toString().length() > 0 ){
                        dailyAnomalyPop();
                        setAlpha(0.2f);
                    }else {
                        ToastUtils.warnShowLong(getApplicationContext(),"请确保时长不为空");
                    }
                }else {
                    ToastUtils.warnShowLong(getApplicationContext(),"预估完成量不为空！！");
                }
                break;
            case R.id.downTime_layout:
                Calendar calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);  // 小时
                int minute = calendar.get(Calendar.MINUTE);     // 分钟
                new TimePickerDialog(MainActivity.this, AlertDialog.THEME_HOLO_LIGHT,new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        actualTime_TV.setText("");
                        String formattedTime = formatTime(hourOfDay, minute);
                        System.out.println("---  时间 ---" + formattedTime);
                        sb.setLength(0);
                        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        // 解析日期时间字符串
                        Date dateTimeObj = null;
                        try {
                            dateTimeObj = dateTimeFormat.parse(startTime_TV.getText().toString());
                            // 提取日期部分并格式化为字符串
                            String dateStr = dateFormat.format(dateTimeObj);
                            System.out.println(dateStr);
                            sb.append(dateStr).append(" ").append(formattedTime).append(":00");
                            boolean  i = getTimeCompareSize(startTime_TV.getText().toString(),sb.toString());
                            System.out.println(i+"----- 时间比较 -----");
                            if (!i){
                                downTime_TV.setText(sb);
                                WorkHourStatistics w = new WorkHourStatistics();
                                w.setStarttime(startTime_TV.getText().toString());
                                w.setUserid(userid);
                                w.setEndtime(downTime_TV.getText().toString());
                                calculateDuration(w);
                            }else {
                                ToastUtils.warnShowLong(getApplicationContext(),"选择时间小于开始时间，请重新选择!!");
                                downTime_TV.setText("请重新选择");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                },hour,minute,true).show();
                break;
            case R.id.layout_close:
                if (reportType == 1 ){   // 有上报其他工时
                    setAlertDialogSize();  //设置 标题及按钮大小
                }else {
                    finish();
                }
                break;
            case R.id.bt_addSublayout:
                i++;
                System.out.println("---- 添加布局 -----");
                String duration;
                if (reportType == 1 || reportType == 3){   //  有其他工作
                     duration = tv_RemainingTime.getText().toString();
                }else {
                    duration = actualTime_TV.getText().toString();
                }
                if (duration.equals("")){
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择时间");
                }else {
                    Double d = div(Double.valueOf(duration),i,2);
                    String s = String.valueOf(d);
                    AddSublayoutToParentlayout();
                    //  更新 已有 布局
                    for (int j = 0; j < textViewList.size(); j++) {
                        TextView textViewToUpdate = textViewList.get(j);
                        textViewToUpdate.setText(s);
                    }
                }
                break;
            case R.id.electricSubmit_BT:
                    if (actualTime_TV.getText().toString().equals("")){
                        ToastUtils.warnShowLong(getApplicationContext(),"请确保工作时长不为空！！");
                    }else {
                        if (getValue()){
                            if (checkProject(projectID) == 0){
                                ToastUtils.warnShowLong(getApplicationContext(),"您添加的项目中跟您打卡项目没有匹配的！！！");
                                return;
                            }
                            if (checkProject(projectID) > 1){
                                ToastUtils.warnShowLong(getApplicationContext(),"您添加的项目中存在多条相同的项目");
                                return;
                            }
                            ElectricReport();
                        }else {
                            ToastUtils.warnShowLong(MainActivity.this,"确保数据不为空！");
                        }
                    }
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }
    private void reStartActivity() {            // 刷新 当前Activity
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    int i ;
    private ArrayList<TextView> textViewList = new ArrayList<>();
    private ArrayList<TextView>  projectTVList = new ArrayList<>();
    // 添加 子布局
//    Spinner spinner;
    public void AddSublayoutToParentlayout(){
        // 创建新的LinearLayout实例
        LinearLayout newLinearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        newLinearLayout.setOrientation(LinearLayout.VERTICAL);
        newLinearLayout.setBackgroundResource(R.drawable.rounded_background);
        layoutParams.setMargins(dpToPx(30),dpToPx(20),dpToPx(30),0);
        newLinearLayout.setLayoutParams(layoutParams);
        // 创建 标题 layout
        LinearLayout titleLinearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams titleLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        titleLayoutParams.setMargins(0,dpToPx(10),0,0);
        titleLinearLayout.setLayoutParams(titleLayoutParams);
        //  项目
        TextView title_tv = new TextView(this);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams( 0, 50, 7);
        title_tv.setLayoutParams(titleParams);
        title_tv.setText("项目"+i);
        title_tv.setTextSize(20);
        title_tv.setGravity(Gravity.LEFT);
        titleParams.setMargins(dpToPx(15),0,0,0);
        titleLinearLayout.addView(title_tv);
        projectTVList.add(title_tv);
        // 创建并添加Button到newLinearLayout
        Button button = new Button(this);
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                0, 40,1);
        button.setLayoutParams(buttonParams);
        button.setText("删  除");
        button.setGravity(Gravity.CENTER);
        button.setBackgroundResource(R.drawable.delect_button);
        buttonParams.setMargins(0,0,dpToPx(5),0);
        button.setTextColor(Color.parseColor("#ffffff"));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i--;
                layout_parent.removeView(newLinearLayout);
                String duration;
                if (reportType == 1 || reportType == 3){   //  有其他工作
                    duration = tv_RemainingTime.getText().toString();
                }else {
                    duration = actualTime_TV.getText().toString();
                }
                if (i != 0){
                    double d = div(Double.valueOf(duration),i,2);  // 被除数不为 0
                    String s = String.valueOf(d);
                    for (int j = 0; j < textViewList.size(); j++) {
                        TextView textViewToUpdate = textViewList.get(j);
                        textViewToUpdate.setText(s);
                    }
                    for (int z = 0; z < projectTVList.size(); z++) {
                        TextView projectTextViewToUpdate = projectTVList.get(z);
                        projectTextViewToUpdate.setText("项目"+i);
                    }
                }
            }
        });
        titleLinearLayout.addView(button);

        // 创建内部的LinearLayout
        LinearLayout internalLinearLayout2 = new LinearLayout(this);
        internalLinearLayout2.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        // 创建并添加TextView到internalLinearLayout2
        TextView textView2 = new TextView(this);
        LinearLayout.LayoutParams textViewParams2 = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
        textViewParams2.setMargins(0,dpToPx(10),0,0);
        textView2.setLayoutParams(textViewParams2);

        textView2.setLayoutParams(textViewParams2);
        textView2.setText("选择项目类型:");
        textView2.setTextSize(20);
        textView2.setGravity(Gravity.CENTER);
        internalLinearLayout2.addView(textView2);

        // 创建并添加Spinner到internalLinearLayout
        Spinner spinner2 = new Spinner(this);
        LinearLayout.LayoutParams spinnerParams2 = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        spinner2.setLayoutParams(spinnerParams2);



        Drawable background2 = ContextCompat.getDrawable(this, R.drawable.assembly_info_background);
        if (background2 != null){
            spinner2.setBackground(background2);
        }
        internalLinearLayout2.addView(spinner2);


        // 创建内部的LinearLayout
        LinearLayout internalLinearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams internalLinearLayoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
        );
        internalLinearLayoutParams.setMargins(0,dpToPx(10),0,0);
        internalLinearLayout.setLayoutParams(internalLinearLayoutParams);
//

        // 创建并添加TextView到internalLinearLayout
        TextView textView = new TextView(this);
        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
        textViewParams.setMargins(0,dpToPx(10),0,0);
        textView.setLayoutParams(textViewParams);

        textView.setLayoutParams(textViewParams);
        textView.setText("请选择项目:");
        textView.setTextSize(20);
        textView.setGravity(Gravity.CENTER);
        internalLinearLayout.addView(textView);

        // 创建并添加Spinner到internalLinearLayout
        Spinner spinner = new Spinner(this);

        typeSpinner(spinner2,spinner);
//        MyAdapter adapter = new MyAdapter(projectnameList2, MainActivity.this);
//        spinner.setAdapter(adapter);

        LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        spinner.setLayoutParams(spinnerParams);
        Drawable background = ContextCompat.getDrawable(this, R.drawable.assembly_info_background);
        if (background != null){
            spinner.setBackground(background);
        }
        internalLinearLayout.addView(spinner);

        // 创建 时长 layout
        LinearLayout timeLinearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams timeLayoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        timeLinearLayout.setLayoutParams(timeLayoutParams);
        TextView timeTitle_tv = new TextView(this);
        LinearLayout.LayoutParams timeTextViewParams = new LinearLayout.LayoutParams(
                0, 50, 1f);
        timeTitle_tv.setLayoutParams(timeTextViewParams);
        timeTitle_tv.setText("工作时长:");
        timeTitle_tv.setTextSize(20);
        timeTitle_tv.setGravity(Gravity.CENTER);
        timeLinearLayout.addView(timeTitle_tv);
        TextView duration_tv = new TextView(this);
        LinearLayout.LayoutParams durationParams = new LinearLayout.LayoutParams( 0, 50 , 3);
        duration_tv.setLayoutParams(durationParams);
        duration_tv.setText("");
        duration_tv.setTextSize(23);
        duration_tv.setTextColor(Color.parseColor("#4169E1"));
        duration_tv.setGravity(Gravity.CENTER);
        timeLinearLayout.addView(duration_tv);
        textViewList.add(duration_tv);

        // 创建 问题 下拉框 布局
        LinearLayout problemTypeLayout = new LinearLayout(this);
        LinearLayout.LayoutParams problemTypeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        problemTypeLayout.setLayoutParams(problemTypeParams);
        TextView problemType_tv = new TextView(this);
        LinearLayout.LayoutParams problemTypeTextViewParams = new LinearLayout.LayoutParams(
                0, 50, 1f);
        problemType_tv.setLayoutParams(problemTypeTextViewParams);
        problemType_tv.setText("问题类型:");
        problemType_tv.setTextSize(20);
        problemType_tv.setGravity(Gravity.CENTER);
        problemTypeLayout.addView(problemType_tv);
        Spinner typeSpinner = new Spinner(this);
        ArrayAdapter<String> causeAdapter = new ArrayAdapter<>(this,R.layout.spinner_item,overdueCause_list);
        typeSpinner.setAdapter(causeAdapter);


        LinearLayout.LayoutParams typeSpinnerParams = new LinearLayout.LayoutParams(
                0, 50, 3f);
        typeSpinner.setLayoutParams(typeSpinnerParams);
        problemTypeLayout.addView(typeSpinner);

        //  异常时间 输入框
        LinearLayout abnormalTimeLayout = new LinearLayout(this);
        abnormalTimeLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        abnormalTimeLayout.setOrientation(LinearLayout.HORIZONTAL);

        TextView tv_abnormalTime = new TextView(this);
        LinearLayout.LayoutParams timeParams = new LinearLayout.LayoutParams(
                0, 50, 1f);
        tv_abnormalTime.setLayoutParams(timeParams);
        tv_abnormalTime.setText("异常时间:");
        tv_abnormalTime.setTextSize(20);
        tv_abnormalTime.setGravity(Gravity.CENTER);
        abnormalTimeLayout.addView(tv_abnormalTime);
        // 时长 输入框
        EditText et_time = new EditText(this);
        LinearLayout.LayoutParams editTimeParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        et_time.setLayoutParams(editTimeParams);
        et_time.setBackgroundResource(R.drawable.edittext_border);
        et_time.setMinHeight(50);
        et_time.setGravity(Gravity.CENTER);
        int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
        et_time.setInputType(inputType);  // 设置输入规则
        et_time.setFilters(new InputFilter[]{lengthfilter});
        editTimeParams.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
        abnormalTimeLayout.addView(et_time);

        // 创建并添加EditText到newLinearLayout
        LinearLayout editTextLinearLayout = new LinearLayout(this);
        editTextLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        editTextLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

        TextView text_et = new TextView(this);
        LinearLayout.LayoutParams textETParams = new LinearLayout.LayoutParams(
                0, 50, 1f);
        text_et.setLayoutParams(textETParams);
        text_et.setText("异常详情(必填):");
        text_et.setTextSize(20);
        text_et.setGravity(Gravity.CENTER);
        editTextLinearLayout.addView(text_et);

        //  问题 输入框
        EditText editText = new EditText(this);
        LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        editText.setLayoutParams(editTextParams);
        editText.setBackgroundResource(R.drawable.edittext_border);
        editText.setMinHeight(85);
        editText.setGravity(Gravity.CENTER);
        editTextParams.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
        editTextLinearLayout.addView(editText);

        // 工作 详情  work_details_Layout
        LinearLayout work_details_Layout = new LinearLayout(this);
        work_details_Layout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        work_details_Layout.setOrientation(LinearLayout.HORIZONTAL);

        TextView work_details_tv = new TextView(this);
        LinearLayout.LayoutParams work_details_params = new LinearLayout.LayoutParams(
                0, 50, 1f);
        work_details_tv.setLayoutParams(work_details_params);
        work_details_tv.setText("工作详情(必填):");
        work_details_tv.setTextSize(20);
        work_details_tv.setGravity(Gravity.CENTER);
        work_details_Layout.addView(work_details_tv);

        // 工作详情 输入框
        EditText work_details_et = new EditText(this);
        LinearLayout.LayoutParams work_details_et_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        work_details_et.setLayoutParams(work_details_et_params);
        work_details_et.setBackgroundResource(R.drawable.edittext_border);
        work_details_et.setMinHeight(85);
        work_details_et.setGravity(Gravity.CENTER);
        work_details_et_params.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
        work_details_Layout.addView(work_details_et);

        typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String abnormal_str = overdueCause_list.get(position);
                if (abnormal_str.equals("无异常")){
                    editText.setText("无异常上报！");
                    editText.setTextColor(Color.parseColor("#000000"));
                    editText.setEnabled(true);

                    et_time.setText("0");
                    et_time.setTextSize(20);
                    et_time.setTextColor(Color.parseColor("#000000"));
                    et_time.setEnabled(false);

                }else {
                    editText.setText(null);
                    editText.setEnabled(true);

                    et_time.setText(null);
                    et_time.setEnabled(true);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });

        newLinearLayout.addView(titleLinearLayout);      //
        newLinearLayout.addView(internalLinearLayout2);
        newLinearLayout.addView(internalLinearLayout);
        newLinearLayout.addView(timeLinearLayout);
        newLinearLayout.addView(problemTypeLayout);
        newLinearLayout.addView(abnormalTimeLayout);
        newLinearLayout.addView(editTextLinearLayout);
        newLinearLayout.addView(work_details_Layout);

        // 将newLinearLayout添加到containerLinearLayout中
        layout_parent.addView(newLinearLayout);
    }
    // 获取 动态 布局值
    boolean isOK ;
    public boolean getValue(){
        isOK = false;
        electricReportBeanArrayList = new ArrayList<>();
        ViewGroup layout_parent = findViewById(R.id.layout_parent);
        if (layout_parent.getChildCount() == 0){
            ToastUtils.warnShowLong(getApplicationContext(),"至少添加一项项目!!!");
        }else {
            for (int i = 0; i < layout_parent.getChildCount(); i++) {
                LinearLayout linearLayout = (LinearLayout) layout_parent.getChildAt(i);
                Log.d(TAG, "getValue:条数："+layout_parent.getChildCount()+" -----linearLayout-----"+linearLayout);
                LinearLayout internalLayout2 = (LinearLayout) linearLayout.getChildAt(1);
                LinearLayout internalLayout = (LinearLayout) linearLayout.getChildAt(2);  //internalLinearLayout
                LinearLayout timeLayout = (LinearLayout) linearLayout.getChildAt(3);      // timeLinearLayout
                LinearLayout problemTypeLayout = (LinearLayout) linearLayout.getChildAt(4); // problemTypeLayout
                LinearLayout abnormalTimeLayout = (LinearLayout) linearLayout.getChildAt(5);   //abnormalTimeLayout
                LinearLayout editTextLayout = (LinearLayout) linearLayout.getChildAt(6);   //editTextLinearLayout
                LinearLayout work_details_Layout = (LinearLayout) linearLayout.getChildAt(7);   //work_details_Layout
                //  获取 子控件
                Spinner sp_type = (Spinner) internalLayout2.getChildAt(1);
                Spinner sp_projectName = (Spinner) internalLayout.getChildAt(1);
                TextView tv_duration = (TextView) timeLayout.getChildAt(1);
                Spinner sp_problemType = (Spinner) problemTypeLayout.getChildAt(1);
                EditText et_time = (EditText) abnormalTimeLayout.getChildAt(1);
                EditText et_describe = (EditText) editTextLayout.getChildAt(1);
                EditText et_workDetails = (EditText) work_details_Layout.getChildAt(1);
                // 获取 子控件 内容
                String str_duration = tv_duration.getText().toString();
                String str_problemType = sp_problemType.getSelectedItem().toString();
                String str_describe = et_describe.getText().toString();
                String str_time = et_time.getText().toString();
                String str_type = sp_type.getSelectedItem().toString();
                String str_work_details = et_workDetails.getText().toString();
                // 判断 内容 是否为空
                if (str_type.equals("选择类型")){
                    isOK = false;
                    return isOK;
                }else if (str_problemType.equals("请选择原因")){
                    isOK = false;
                    return isOK;
                }else if(str_time.isEmpty()){
                    isOK = false;
                    return isOK;
                } else if (str_describe.isEmpty()){
                    isOK = false;
                    return isOK;
                }else if (str_work_details.isEmpty()){
                    isOK = false;
                    return isOK;
                }else {
                    // 获取自定义spinner 内容
                    Object str_projectName = sp_projectName.getSelectedItem();
                    Long projectCodeid = ((ProjectSpinner)str_projectName).getProjectId();
                    if (projectCodeid == 0){
                        isOK = false;
                        return isOK;
                    }
                    String str_projectName2 = ((ProjectSpinner)str_projectName).getProjectName();

                    System.out.println("项目"+str_projectName2+
                            "----项目id：---"+ projectCodeid +
                            "**** 时长：****"+str_duration+
                            "===== 问题类型：===="+str_problemType+
                            "~~~~ wenti描述：~~~~~"+str_describe+
                            "~~~~ 工作详情：~~~~~"+str_work_details);

                    electricReportBeanArrayList.add(
                            new CustomElectricReportBean(projectCodeid, str_duration,
                                    str_problemType, str_time, str_describe, str_work_details));
                    isOK = true;

                }
            }
        }
        return isOK;
    }
    // 判断是否重复 项目ID
    public int checkProject(Long prodectID) {
        Set<Long> ids = new HashSet<>();
        boolean hasDuplicate = false;
        boolean hasMatchingId = false;

        for (CustomElectricReportBean bean : electricReportBeanArrayList) {
            Long id = bean.getId();
            if (!ids.add(id)) {
                hasDuplicate = true;
            }
            if (id.equals(prodectID)) {
                hasMatchingId = true;
            }
        }

        if (hasDuplicate) {
            System.out.println("存在重复的ID:");
            return 2;
        } else if (hasMatchingId) {
            System.out.println("找到匹配的ID");
            return 1;
        } else {
            System.out.println("没有重复的ID且没有找到匹配的ID");
            return 0;
        }
    }

    //  电气 装配 日报上报
    List<WorkHourStatistics> workHourStatisticsList = new ArrayList<>();
    public void ElectricReport(){
        String completionProgress_str = completionProgress_ET.getText().toString();
        String str_suggest = et_suggest.getText().toString();
        if (completionProgress_str.length() == 0){
            ToastUtils.warnShowLong(getApplicationContext(),"预估完成量不为空！");
        }else {
            if (electricReportBeanArrayList.size() > 0){
                for (int j = 0; j < electricReportBeanArrayList.size(); j++) {
                    String startTime_str = startTime_TV.getText().toString();
                    Long projectId = electricReportBeanArrayList.get(j).getId();
                    String duration_str = electricReportBeanArrayList.get(j).getEl_duration();
                    String remark_str = electricReportBeanArrayList.get(j).getEl_problemType();
                    String abnormal_time = electricReportBeanArrayList.get(j).getAbnormal_time();
                    String details_str = electricReportBeanArrayList.get(j).getEl_describe();
                    String worker_details_str = electricReportBeanArrayList.get(j).getEl_worker_details();

                    if (projectId.equals(projectID)){     //
                        if (type == 1){    //  1 为正常下班
                            workHourStatisticsList.add(new WorkHourStatistics(androidId, workhourid, producedate, deptId, startTime_str, endTime_str,
                                    userid, projectId, duration_str, remark_str, abnormal_time, details_str, completionProgress_str, str_suggest,
                                    electricAssablyId, worker_details_str ));
                        }else {
                            String downTime_str = downTime_TV.getText().toString();
                            workHourStatisticsList.add(new WorkHourStatistics(androidId, workhourid, producedate, deptId, startTime_str, downTime_str,
                                    userid, projectId, duration_str, remark_str, abnormal_time, details_str, completionProgress_str, str_suggest,
                                    electricAssablyId, worker_details_str ));
                        }

                    }else {
                        if (type == 1){
                            workHourStatisticsList.add(new WorkHourStatistics(androidId, workhourid, producedate, deptId, startTime_str, endTime_str,
                                    userid, projectId, duration_str, remark_str, abnormal_time, details_str, completionProgress_str, str_suggest, worker_details_str ));
                        }else {
                            String downTime_str = downTime_TV.getText().toString();
                            workHourStatisticsList.add(new WorkHourStatistics(androidId, workhourid, producedate, deptId, startTime_str, downTime_str,
                                    userid, projectId, duration_str, remark_str, abnormal_time, details_str, completionProgress_str, str_suggest, worker_details_str ));
                        }
                    }
//                    if (j == 0){
//                        WorkHourStatistics w = new WorkHourStatistics();
//                        w.setBelowSerialNo(androidId);
//                        if (type == 1){
//                            w.setEndtime(endTime_str);  // 结束时间
//                        }else {
//                            w.setEndtime(downTime_TV.getText().toString());
//                        }
//                        w.setWorkhourid(workhourid);
//                        w.setProjectId(electricReportBeanArrayList.get(j).getId());
//                        w.setDuration(electricReportBeanArrayList.get(j).getEl_duration());
//                        w.setRemark(electricReportBeanArrayList.get(j).getEl_problemType());
//                        w.setAbnormalWorkingHours(electricReportBeanArrayList.get(j).getAbnormal_time());
//                        w.setDetails(electricReportBeanArrayList.get(j).getEl_describe());
//                        w.setPercentage(completionProgress_str);
//                        w.setRationalizationProposal(str_suggest);
//                        updateWorkHourStatistics(w);    // 修改 工时 信息
//                    }else {
//                        WorkHourStatistics w = new WorkHourStatistics();
//                        w.setUpperSerialNo(androidId);
//                        w.setBelowSerialNo(androidId);
//                        w.setDeptId(deptId);
//                        w.setProducedate(producedate);
//                        w.setStarttime(startTime_TV.getText().toString());
//                        if (type == 1){
//                            w.setEndtime(endTime_str);  // 结束时间
//                        }else {
//                            w.setEndtime(downTime_TV.getText().toString());
//                        }
//                        w.setDuration(electricReportBeanArrayList.get(j).getEl_duration());
//                        w.setUserid(userid);
//                        w.setProjectId(electricReportBeanArrayList.get(j).getId());
//                        w.setRemark(electricReportBeanArrayList.get(j).getEl_problemType());
//                        w.setAbnormalWorkingHours(electricReportBeanArrayList.get(j).getAbnormal_time());
//                        w.setDetails(electricReportBeanArrayList.get(j).getEl_describe());
//                        w.setElectricalAssemblyId(electricAssablyId);
//                        w.setClocktype("电气装配");
//                        w.setStatus("已下班");
//                        w.setPercentage(completionProgress_str);
//                        workClockIn(w);
//                    }
                }
                System.out.println("----电气装配shangbao数据-----"+workHourStatisticsList);
                addWorkClockInBatch(workHourStatisticsList);

            }
        }

    }

    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
//                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:  "+statusCode);
            }
        });
    }

    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner (Spinner spinner2 ,Spinner spinner){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
//        typeSpinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(typeSpinner_adapter);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                }else {
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setElectricalBcode(electricBCODE);
                    selectProjectCode(projectType,spinner);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    private  List<ProjectSpinner> projectnameList2 = null;  // 项目 列表
    public void selectProjectCode(ProjectType projectType, Spinner spinner){
        API.selectProjectCode(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());
                        System.out.println("----123456789------"+projectManagementList);
//                        projectnameList2.clear();
                        projectnameList2 = new ArrayList<>();
                        if (projectManagementList.size() > 0){
                            for (ProjectManagement p : projectManagementList) {
                                projectnameList2.add(new ProjectSpinner(p.getProjectname(),
                                        p.getProductacode(),
                                        p.getProjectid(),
                                        p.getDeptid()));
                            }
                        }else {
                            projectnameList2.add(new ProjectSpinner("",
                                    "无匹配B码",
                                    0L,
                                    0L));
                            ToastUtils.warnShowLong(MainActivity.this,"该类型下没有对应B码项目！");
                        }

                        Log.d(TAG, "run: ----projectnameList2-----"+projectnameList2);
                        setProject(projectnameList2,spinner);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void setProject(List<ProjectSpinner> projectnameList2 ,Spinner spinner){
        MyAdapter adapter = new MyAdapter(projectnameList2, MainActivity.this);
        spinner.setAdapter(adapter);
    }

    //  项目下拉框
    public void findProjectName(ProjectManagement p){
        API.findProjectName(p, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("----- 所有项目：-------"+result);
                        projectnameList.clear();
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagements = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType() );
                        if (projectManagements != null){
                            for (int i = 0; i < projectManagements.size(); i++) {
                                if (!projectManagements.get(i).getStatus().equals("已完成")){
                                    projectnameList.add(new ProjectSpinner(projectManagements.get(i).getProductacode(),
                                            projectManagements.get(i).getProjectname(),
                                            projectManagements.get(i).getProjectid()));
                                }
                            }
                            System.out.println("----- 项目 数据------"+projectnameList);
                        }else {
                            ToastUtils.warnShowLong(MainActivity.this,"网络不稳定请重试！");
                        }
                    }
                });

            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 时间  格式转化
    private String formatTime(int hourOfDay, int minute) {
        // 使用String.format来格式化时间
        return String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
    }

    //  电气 装配 批量添加
    public void addWorkClockInBatch(List<WorkHourStatistics> workHourStatisticsList){
        API.addWorkClockInBatch(workHourStatisticsList, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("----批量添加成功-----"+result);
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        Long code = j.getLong("code");
                        if (code == 200){
                            ToastUtils.successShowLong(getApplicationContext(),msg);
                            Intent intent = new Intent(MainActivity.this,HomePageActivity.class);
                            setResult(Activity.RESULT_OK,intent);
                            finish();
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(), msg);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 上报 信息
    public void updateWorkHourStatistics(WorkHourStatistics w){
        API.updateWorkHourStatistics(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        switch (msg){
                            case "操作成功":
                                ToastUtils.successShowLong(getApplicationContext(),"日报上报成功！");
                                if (dailyAnomaly_pop != null){
                                    dailyAnomaly_pop.dismiss();
                                }
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        //  返回首页
                                        Intent intent = new Intent(MainActivity.this,HomePageActivity.class);
                                        setResult(Activity.RESULT_OK,intent);
                                        finish();
                                    }
                                },300);
                                break;
                            case "已下班":
                                ToastUtils.warnShowLong(getApplicationContext(),"该工单已打下班卡，无法重复修改");
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 根据 workid 。。。。
    public void findWorkHour(WorkHourStatistics workHourStatistics){
        electricBCODE = null;
        API.clockInStatus(workHourStatistics, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                System.out.println("====gongdan 信息======"+workHourList);
                if (workHourList != null && workHourList.size() > 0){
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            projectID = workHourList.get(0).getProjectId();
                            electricBCODE = workHourList.get(0).getElectricalBcode();
                            EmployeeName_TV.setText(workHourList.get(0).getNickName());
                            group2_TV.setText(workHourList.get(0).getDeptName());
                            cardNumber2_TV.setText(workHourList.get(0).getIcCard());
                            startTime_TV.setText(workHourList.get(0).getStarttime());
                            endTime_TV.setText(endTime_str);
                            clocktype = workHourList.get(0).getClocktype();
                            clockType_TV.setText(clocktype);
                            projectName_TV.setText(workHourList.get(0).getProjectName());
                            aCode_TV.setText(workHourList.get(0).getProductAcode());
                            tv_electric_name.setText(electricBCODE);
                            tv_electric_specification.setText(workHourList.get(0).getElectricalspecifications());
                            tv_assembly_name.setText(workHourList.get(0).getAssemblyName());
                            electricAssablyId = workHourList.get(0).getElectricalAssemblyId();

                            switch (clocktype){
                                case "机械装配":
                                    layout_aCode.setVisibility(View.VISIBLE);
                                    layout_projectName.setVisibility(View.VISIBLE);
                                    infoSubmit_BT.setVisibility(View.VISIBLE);
                                    layout_otherWork.setVisibility(View.GONE);
                                    layout_parent.setVisibility(View.GONE);
                                    bt_addSublayout.setVisibility(View.GONE);
                                    electricSubmit_BT.setVisibility(View.GONE);
                                    tv_timeDeductTips.setVisibility(View.GONE);
                                    layout_other.setVisibility(View.GONE);
                                    layout_electric_name.setVisibility(View.GONE);
                                    layout_specification.setVisibility(View.GONE);
                                    layout_suggestion.setVisibility(View.GONE);
                                    showSpinner = 1;
                                    break;
                                case "电气装配":
                                    layout_electric_name.setVisibility(View.VISIBLE);
                                    layout_specification.setVisibility(View.VISIBLE);
                                    layout_otherWork.setVisibility(View.VISIBLE);
                                    layout_parent.setVisibility(View.VISIBLE);
                                    bt_addSublayout.setVisibility(View.VISIBLE);
                                    electricSubmit_BT.setVisibility(View.VISIBLE);
                                    infoSubmit_BT.setVisibility(View.GONE);
                                    layout_projectName.setVisibility(View.VISIBLE);
                                    layout_aCode.setVisibility(View.VISIBLE);
                                    tv_timeDeductTips.setVisibility(View.GONE);
                                    layout_other.setVisibility(View.GONE);
                                    layout_suggestion.setVisibility(View.VISIBLE);
                                    showSpinner = 2;
                                    break;
                                default:
                                    break;
                            }
                            producedate = workHourList.get(0).getProducedate();
                            deptId = workHourList.get(0).getDeptId();
                            //  计算时长
                            WorkHourStatistics w = new WorkHourStatistics();
                            w.setStarttime(workHourList.get(0).getStarttime());
                            w.setUserid(workHourList.get(0).getUserid());
                            userid = workHourList.get(0).getUserid();
                            if (type == 1){
                                w.setEndtime(endTime_str);
                                calculateDuration(w);

                                //  查找 是否有 其他工作
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        WorkHourStatistics w2 = new WorkHourStatistics();
                                        w2.setStarttime(workHourList.get(0).getStarttime());
                                        w2.setClocktype("其他工作");
                                        otherWorkInfo(w2);
                                    }
                                },300);
                            }
                        }
                    });
                }
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    Double otherTimeSum;
    public void otherWorkInfo(WorkHourStatistics w){
        API.clockInStatus(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        otherTimeSum = 0.0;
                        JSONObject j = JSONObject.parseObject(result);
                        List<WorkHourStatistics> wList = new Gson().fromJson(j.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        if (wList.size() > 0){
                            // 计算 其他工作时间
                        for (int k = 0; k < wList.size() ; k++) {
                            Double d_duration = Double.valueOf(wList.get(k).getDuration());
                            otherTimeSum = add(otherTimeSum,d_duration);
                        }
                        System.out.println("-----有-其他工作------"+otherTimeSum);
                            tv_otherTime.setText(String.valueOf(otherTimeSum));
                            Double d = Double.parseDouble(actualTime_TV.getText().toString());
                            Double value = sub(d, otherTimeSum);
                            tv_RemainingTime.setText(String.valueOf(value));
                            layout_other.setVisibility(View.VISIBLE);
                            tv_timeDeductTips.setVisibility(View.VISIBLE);
                            layout_otherWork.setVisibility(View.GONE);
                            reportType = 3;
                        }
                    }
                });

            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  根据 开始 + 结束 + useid 查询工时
    public void calculateDuration(WorkHourStatistics w){
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                System.out.println("----- 实际工时-------"+result);
                actualTime_str = jsonObject.getString("msg");
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        actualTime_TV.setText(actualTime_str);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    @Override
    public void onBackPressed() {   //  监听  界面返回
        if (reportType == 1 ){   // 有上报其他工时
            setAlertDialogSize();
        }else {
            MainActivity.super.onBackPressed();
        }
    }

    @SuppressLint("ResourceAsColor")
    public void setAlertDialogSize( ){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("是否要退出")
                .setMessage("您还没填写日报信息!!!")
                .setIcon(R.drawable.danger)
                .setCancelable(true)
                .setPositiveButton("否", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {  // 右
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();

        //   设置 按钮 大小
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(30);
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setPadding(0,20,20,10);
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(royalblue);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(30);
        try {     // 设置标题大小）
            //获取mAlert对象
            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
            mAlert.setAccessible(true);
            Object mAlertController = mAlert.get(dialog);

            //获取mTitleView并设置大小颜色
            Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
            mTitle.setAccessible(true);
            TextView mTitleView = (TextView) mTitle.get(mAlertController);
            mTitleView.setTextSize(40);
            mTitleView.setTextColor(Color.RED);

            //获取mMessageView并设置大小颜色
            Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
            mMessage.setAccessible(true);
            TextView mMessageView = (TextView) mMessage.get(mAlertController);
            mMessageView.setTextColor(Color.RED);
            mMessageView.setTextSize(30);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    // 提示 弹出框
    PopupWindow tips_pop;
    public void tipsPop(){
        View tips_view = getLayoutInflater().inflate(R.layout.tips_pop,null);
        Button tipsOk_BT,tipsCancel_BT;
        tipsOk_BT = tips_view.findViewById(R.id.tipsOk_BT);
        tipsCancel_BT = tips_view.findViewById(R.id.tipsCancel_BT);
        tipsOk_BT.setOnClickListener(new View.OnClickListener() {  // 确定
            @Override
            public void onClick(View v) {
                tips_pop.dismiss();
                startActivity(new Intent(getApplicationContext(),HomePageActivity.class));
                finish();
            }
        });
        tipsCancel_BT.setOnClickListener(new View.OnClickListener() {  // 取消
            @Override
            public void onClick(View v) {
                tips_pop.dismiss();
                setAlpha(1.0f);
            }
        });
        int width = ScreenUtils.getWidth(MainActivity.this);
        tips_pop = new PopupWindow
                (tips_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        tips_pop.setTouchable(true);
        tips_pop.setFocusable(true);
        tips_pop.setOutsideTouchable(true);
        tips_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    //  每日异常上报弹窗
    PopupWindow dailyAnomaly_pop;
    ArrayAdapter<String> cause_adapter;
    public void dailyAnomalyPop() {
        View dailyAnomaly_view = getLayoutInflater().inflate(R.layout.anomaly_info_submit_pop,null);
        Spinner sp_abnormal = dailyAnomaly_view.findViewById(R.id.sp_abnormal);
        if (overdueCause_list.size() > 0){
            cause_adapter = new ArrayAdapter<>(this,R.layout.spinner_item,overdueCause_list);
        }else {
            setAlpha(1.0f);
            ToastUtils.warnShowLong(MainActivity.this,"网络不佳，请刷新界面！！");
        }
        sp_abnormal.setAdapter(cause_adapter);
        EditText et_ProblemNote = dailyAnomaly_view.findViewById(R.id.et_ProblemNote);
        EditText et_abnormalTime = dailyAnomaly_view.findViewById(R.id.et_abnormalTime);  ///  异常时间
        int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
        et_abnormalTime.setInputType(inputType);  // 设置输入规则
        et_abnormalTime.setFilters(new InputFilter[]{lengthfilter});
        Button bt_abnormalSubmit = dailyAnomaly_view.findViewById(R.id.bt_abnormalSubmit);
        EditText et_suggestion = dailyAnomaly_view.findViewById(R.id.et_suggestion);
        sp_abnormal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemSelected: ----异常选择----"+overdueCause_list.get(position));
                String abnormal_str = overdueCause_list.get(position);
                if (abnormal_str.equals("无异常")){
                    et_abnormalTime.setText("0");
                    et_abnormalTime.setTextColor(Color.parseColor("#000000"));
                    et_ProblemNote.setText("无异常上报！");
                    et_ProblemNote.setTextColor(Color.parseColor("#000000"));
                    et_abnormalTime.setEnabled(false);
                    et_ProblemNote.setEnabled(false);
                }else {
                    et_abnormalTime.setText(null);
                    et_ProblemNote.setText(null);
                    et_abnormalTime.setEnabled(true);
                    et_ProblemNote.setEnabled(true);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });

        bt_abnormalSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_suggestion = et_suggestion.getText().toString();
                String abnomaly = sp_abnormal.getSelectedItem().toString();
                String completionProgress_str = completionProgress_ET.getText().toString();
                String problementNote = et_ProblemNote.getText().toString();
                String str_abnormalTime = et_abnormalTime.getText().toString();
                WorkHourStatistics w = new WorkHourStatistics();
                if (abnomaly.equals("请选择原因") || problementNote.isEmpty() || str_abnormalTime.isEmpty()){
                    ToastUtils.warnShowLong(MainActivity.this,"请确保必填项不为空！！");
                }else {
                    double actualTime = Double.parseDouble(actualTime_TV.getText().toString());
                    double abnormalTime = Double.parseDouble(et_abnormalTime.getText().toString());
                    if (actualTime < abnormalTime) {
                        ToastUtils.warnShowLong(getApplicationContext(), "异常时间 大于 打卡时间");
                        return;
                    }
                    if (type == 1){
                        w.setEndtime(endTime_str);  // 结束时间
                    }else {
                        w.setEndtime(downTime_TV.getText().toString());
                    }
                        w.setBelowSerialNo(androidId);
                        w.setDuration(actualTime_TV.getText().toString());  // 时长
                        w.setWorkhourid(workhourid);
                        w.setPercentage(completionProgress_str);
                        w.setRemark(abnomaly);
                        w.setAbnormalWorkingHours(str_abnormalTime);
                        w.setDetails(problementNote);
                        w.setRationalizationProposal(str_suggestion);
                        updateWorkHourStatistics(w);//  修改
//                    dailyAnomaly_pop.dismiss();
                }
            }
        });
        ImageView iv_back = dailyAnomaly_view.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dailyAnomaly_pop.dismiss();
            }
        });
        int width = ScreenUtils.getWidth(MainActivity.this);
        dailyAnomaly_pop = new PopupWindow
                (dailyAnomaly_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        dailyAnomaly_pop.setTouchable(true);
        dailyAnomaly_pop.setFocusable(true);
        dailyAnomaly_pop.setOutsideTouchable(true);
        dailyAnomaly_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        dailyAnomaly_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
    }


    int reportType ;  // 1:  其他 工作  2：日常上报  3: 有上报其他工作异常退出
    //   其他工时上报 弹窗
    PopupWindow otherReport_pop;
    ArrayAdapter<String> otherHours_adapter;
    public void otherHoursReportPop(){
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                View contentView = getLayoutInflater().inflate(R.layout.other_hours_report,null);
                int width = ScreenUtils.getWidth(getApplicationContext());
                otherReport_pop = new PopupWindow
                        (contentView, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
                otherReport_pop.setTouchable(true);
                otherReport_pop.setFocusable(true);
                otherReport_pop.setOutsideTouchable(true);
                Spinner overdueReason_SP = contentView.findViewById(R.id.overdueReason_SP);
                EditText et_JobContent = contentView.findViewById(R.id.et_JobContent);
                EditText et_otherCause = contentView.findViewById(R.id.et_otherCause);  // 详情
                otherHours_adapter = new ArrayAdapter<>(MainActivity.this,R.layout.spinner_item,overdueCause_list);
                overdueReason_SP.setAdapter(otherHours_adapter);
                overdueReason_SP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String abnormal_str = overdueCause_list.get(position);
                        if (abnormal_str.equals("无异常")){
                            et_otherCause.setText("无异常上报！");
                            et_otherCause.setTextColor(Color.parseColor("#000000"));
                            et_otherCause.setEnabled(false);
                        }else {
                            et_otherCause.setText(null);
                            et_otherCause.setEnabled(true);
                        }
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {}
                });

                EditText et_otherHours = contentView.findViewById(R.id.et_otherHours); // 时长
                // 限制 小数点后一位
                InputFilter lengthfilter = new InputFilter() {
                    public CharSequence filter(CharSequence source, int start, int end,
                                               Spanned dest, int dstart, int dend) {
                        // 删除等特殊字符，直接返回
                        if ("".equals(source.toString())) {
                            return null;
                        }
                        String dValue = dest.toString();

                        String sValue = source.toString();
                        if (dValue.length() == 0 && sValue.length() == 1) {
                            if (!Character.isDigit(sValue.charAt(0))) {    // 第一个字符必须是数字
                                return "";
                            }
                        }

                        String[] splitArray = dValue.split("\\.");
                        if (splitArray.length > 1) {
                            String dotValue = splitArray[1];
                            int diff = dotValue.length() + 1 - 2;
                            if (diff > 0) {
                                return source.subSequence(start, end - diff);
                            }
                        }
                        return null;
                    }
                };
                et_otherHours.setFilters(new InputFilter[]{lengthfilter});  // 限制输入内容
                ImageView iv_close = contentView.findViewById(R.id.iv_close);
                iv_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        otherReport_pop.dismiss();
                    }
                });

                Button otherHoursSub_BT = contentView.findViewById(R.id.otherHoursSub_BT);

                otherReport_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
                otherHoursSub_BT.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        str_otherHours = et_otherHours.getText().toString();
                        String str_otherCause = et_otherCause.getText().toString();
                        String str_JobContent = et_JobContent.getText().toString();
                        String str_overdueReason = overdueReason_SP.getSelectedItem().toString();
                        double d_actualTime = Double.parseDouble(actualTime_TV.getText().toString());
                        if (str_otherHours.length() == 0 || str_JobContent.equals("") || str_otherCause.isEmpty()  ){
                            ToastUtils.warnShowLong(getApplicationContext(),"请确保上报内容不为空");
                        }else {
                            if (Double.parseDouble(str_otherHours) > d_actualTime){
                                ToastUtils.warnShowLong(getApplicationContext(),"填写的时间大于刷卡时间");
                                et_otherHours.setText("");
                            }else {
                                reportType = 1;
                                Double num = Double.parseDouble("0"+str_otherHours);

                                WorkHourStatistics w = new WorkHourStatistics();
                                w.setDeptId(deptId);
                                w.setProducedate(producedate);
                                w.setStarttime(startTime_TV.getText().toString());
                                if (type == 1){
                                    w.setEndtime(endTime_str);  // 结束时间
                                }else {
                                    w.setEndtime(downTime_TV.getText().toString());
                                }
                                w.setUpperSerialNo(androidId);
                                w.setBelowSerialNo(androidId);
                                w.setDuration(String.valueOf(num) );
                                w.setUserid(userid);
                                w.setClocktype("其他工作");
                                w.setRemark(str_overdueReason);
                                w.setDetails(str_otherCause);
                                w.setWorkDetails(str_JobContent);
                                w.setStatus("已下班");
                                workClockIn(w);

                            }

                        }
                    }
                });

            }
        });
    }
    public List<String> overdueCause_list = new ArrayList<>();
    //  异常原因
    public void abnormalCause(FactoryAbnormalIssues f){
        overdueCause_list.clear();
        API.abnormalCause(f, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<FactoryAbnormalIssues> factoryAbnormalIssuesList = new Gson().fromJson(j.getString("data"), new TypeToken<List<FactoryAbnormalIssues>>(){}.getType());
//                        overdueCause_list.clear();
                        overdueCause_list.add("请选择原因");
                        if (factoryAbnormalIssuesList.size() > 0){
                            for (int i = 0; i < factoryAbnormalIssuesList.size(); i++) {
                                overdueCause_list.add(factoryAbnormalIssuesList.get(i).getAbnormalissues());
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 工时 上报
    public void workClockIn(WorkHourStatistics w){
        API.addWorkClockIn( w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String code = j.getString("code");
                        if (code.equals("200")){
                            if (reportType == 1){
                                if(otherReport_pop != null){
                                    otherReport_pop.dismiss();
                                }

                                System.out.println("---有其他工作时-----");
                                tv_timeDeductTips.setVisibility(View.VISIBLE);
                                layout_other.setVisibility(View.VISIBLE);
//                                layout_otherWork.setVisibility(View.GONE);

//                                Double d = Double.parseDouble(actualTime_TV.getText().toString());
//                                System.out.println("---dddddddd-----"+d);
//                                Double value = sub(d, Double.parseDouble(str_otherHours));   //减法
//                                String time = String.valueOf(value);
//                                tv_otherTime.setText(str_otherHours);
//                                tv_RemainingTime.setText(time);
                            }
                            ToastUtils.successShowLong(getApplicationContext(),"上报成功!!!");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    /**
     * 对比  两个时间
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean getTimeCompareSize(String startTime, String endTime) {
        int i = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //正常情况下的逻辑操作.
                i = 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (i == 1 || i == 2) {
            return true;
        } else {
            return false;
        }
    }

    //  限制 输入框输入 1~100 内数字
    public TextWatcher inputWatch(final EditText input) {
        return new TextWatcher() {
            private String outStr = ""; //这个值存储输入超过两位数时候显示的内容
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String edit = s.toString();
                if (edit.length() ==2 && Integer.parseInt(edit)>=10){
                    outStr = edit;
                }
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String words = s.toString();
                //首先内容进行非空判断，空内容（""和null）不处理
                if (!TextUtils.isEmpty(words)) {
                    //1-100的正则验证
                    Pattern p = Pattern.compile("^(100|[1-9]\\d|\\d)$");
                    Matcher m = p.matcher(words);
                    if (m.find() || ("").equals(words)) {
                        //这个时候输入的是合法范围内的值
                    } else {
                        if (words.length() > 2) {
                            //若输入不合规，且长度超过2位，继续输入只显示之前存储的outStr
                            input.setText(outStr);
                            //重置输入框内容后默认光标位置会回到索引0的地方，要改变光标位置
                            input.setSelection(2);
                        }
                        ToastUtils.warnShowLong(MainActivity.this,"请输入范围在1-100之间的整数");
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //这里的处理是不让输入0开头的值
                String words = s.toString();
                //首先内容进行非空判断，空内容（""和null）不处理
                if (!TextUtils.isEmpty(words)) {
                    if (Integer.parseInt(s.toString()) <= 0) {
                        input.setText("");
                        ToastUtils.warnShowLong(MainActivity.this,"请输入范围在1-100之间的整数");
                    }
                }
            }
        };
    }
    InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();

            String sValue = source.toString();
            if (dValue.length() == 0 && sValue.length() == 1) {
                if (!Character.isDigit(sValue.charAt(0))) {    // 第一个字符必须是数字
                    return "";
                }
            }

            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - 2;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dailyAnomaly_pop != null){
            dailyAnomaly_pop.dismiss();
        }

    }
    //    dp  转化为  像素
    public int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
    // 两数 相除 精度
    public double div(double a,int b,int scale){
        BigDecimal b1 = new BigDecimal(Double.toString(a));
        BigDecimal b2 = new BigDecimal(Double.toString(b));
        return b1.divide(b2, scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
//     减法
    public double sub(double a,double b) {
        BigDecimal b1 = new BigDecimal(Double.toString(a));
        BigDecimal b2 = new BigDecimal(Double.toString(b));
        return b1.subtract(b2).doubleValue();
    }
    //  两个 double 相加精度丢失 问题
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }



}